package com.hy.example.shared.distribute.lock;

import java.util.Optional;
import java.util.concurrent.locks.Lock;
import java.util.function.Supplier;

/**
 * 分布式锁定义, 扩展 @see java.util.concurrent.locks.Lock 提供 JDK Lock 一致的使用体验
 */
public interface DistLock extends Lock {
    default void tryRun(Runnable runnable) {
        if (!tryLock()) {
            return;
        }
        try {
            runnable.run();
        } finally {
            unlock();
        }
    }

    default <T> Optional<T> trySupply(Supplier<T> supplier) {
        if (!tryLock()) {
            return Optional.empty();
        }
        try {
            return Optional.ofNullable(supplier.get());
        } finally {
            unlock();
        }
    }


    default void run(Runnable runnable) {
        try {
            lock();
            runnable.run();
        } finally {
            unlock();
        }
    }

    default <T> T supply(Supplier<T> supplier) {
        try {
            lock();
            return supplier.get();
        } finally {
            unlock();
        }
    }
}
